package com.zmh.thread.muilt_thread_print;

/**
 * ���߳̽����ӡ �����������ࣩ
 *
 * @author zmh
 * @create 2018-10-24 ����11:11
 **/
public class MuiltThreadPrint_1 {

    public MuiltThreadPrint_1(boolean flag) {
        this.flag = flag;
    }

    boolean flag;

    static class A extends Thread {
        private MuiltThreadPrint_1 muiltThreadPrint;

        public A(MuiltThreadPrint_1 muiltThreadPrint) {
            this.muiltThreadPrint = muiltThreadPrint;
        }

        @Override
        public void run() {
            try {
                int i = 1;

                while (i <= 10000) {
                    synchronized (muiltThreadPrint) {
                        if (muiltThreadPrint.flag) {
                            System.out.println("A");
                            i++;
                            muiltThreadPrint.flag = false;
                            muiltThreadPrint.notify();
                        } else {
                            muiltThreadPrint.wait();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class B extends Thread {
        private MuiltThreadPrint_1 muiltThreadPrint;

        public B(MuiltThreadPrint_1 muiltThreadPrint) {
            this.muiltThreadPrint = muiltThreadPrint;
        }

        @Override
        public void run() {
            try {
                int i = 1;

                while (i <= 10000) {
                    synchronized (muiltThreadPrint) {
                        if (!muiltThreadPrint.flag) {
                            System.out.println("B");
                            i++;
                            muiltThreadPrint.flag = true;
                            muiltThreadPrint.notify();
                        } else {
                            muiltThreadPrint.wait();
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MuiltThreadPrint_1 muiltThreadPrint = new MuiltThreadPrint_1(true);
        A a = new A(muiltThreadPrint);
        B b = new B(muiltThreadPrint);
        a.start();
        Thread.sleep(1000);
        b.start();
    }
}

